package cn.edu.sasu;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import cn.edu.sasu.http.HttpUrl;
import cn.edu.sasu.http.HttpUserService;
import cn.edu.sasu.utils.StringUtil;

public class RegisterActivity extends Activity {
	private EditText et_number, et_password, et_countersign_password;
	private Map<String, String> params;
	private CheckBox cb_agree;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initView();
	}

	private void initView() {
		et_countersign_password = (EditText) findViewById(R.id.et_countersign_password);
		et_number = (EditText) findViewById(R.id.et_number);
		et_password = (EditText) findViewById(R.id.et_password);
		cb_agree = (CheckBox) findViewById(R.id.cb_agree);

	}

	public void register(View view) {
		if (!cb_agree.isChecked()) {
			Toast.makeText(RegisterActivity.this, R.string.i_agree,
					Toast.LENGTH_SHORT).show();// 我同意
			return;
		}
		String number = et_number.getText().toString();
		String password = et_password.getText().toString();
		String countersignPassword = et_countersign_password.getText()
				.toString();

		String address = "四川省达州市";// 地址

		if (StringUtil.isBlank(number)) {
			Toast.makeText(RegisterActivity.this, R.string.enter_username,
					Toast.LENGTH_SHORT).show();// 请输入用户名
			return;
		}
		if (StringUtil.isBlank(password)) {
			Toast.makeText(RegisterActivity.this, R.string.enter_password,
					Toast.LENGTH_SHORT).show();// 请输入密码
			return;
		}
		if (password.length() < 6 || password.length() > 11) {
			Toast.makeText(RegisterActivity.this, R.string.password_no_ok,
					Toast.LENGTH_SHORT).show();
			et_password.setText(null);
			et_countersign_password.setText(null);
			return;
		}
		if (StringUtil.isBlank(countersignPassword)) {
			Toast.makeText(RegisterActivity.this,
					R.string.enter_again_password, Toast.LENGTH_SHORT).show();
			return;
		}
		if (!countersignPassword.equals(password)) {
			Toast.makeText(RegisterActivity.this,
					R.string.enter_twice_password_no_ok, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		params = new HashMap<String, String>();
		params.put("user.userNumber", number + "@163.com");
		params.put("user.userName", number);
		params.put("user.userPassword", password);
		params.put("user.userAddress", address);
		String data = new HttpUserService().requestByPost(
				HttpUrl.url(HttpUrl.USER_REGISTER), params);
		Toast.makeText(RegisterActivity.this, data, Toast.LENGTH_SHORT).show();
		if (data.endsWith(getString(R.string.register_ok))) {
			this.setResult(RESULT_OK);
			finish();
		}

	}

	public void returnLogin(View view) {
		this.setResult(RESULT_OK);
		finish();
	}
}